<?php

class TamdiemController extends Zend_Controller_Action {

    const BASE_URL = "http://www.tamdiem.net/";
    const WORLD_MODULE_BASE_URL = "http://www.tamdiem.net/the-gioi/";
    const VIETNAM_DIE_MODULE_BASE_URL = "http://www.tamdiem.net/viet-nam/";
    const RELAX_MODULE_BASE_URL = "http://www.tamdiem.net/giai-tri/";
    const DOCUMENT_MODULE_BASE_URL = "http://www.tamdiem.net/tu-lieu/";
    const IEADS_MODULE_BASE_URL = "http://www.tamdiem.net/doc-dao-sang-tao/";
    const MYEYE_MODULE_BASE_URL = "http://www.tamdiem.net/my-eye/";
    const TOUR_MODULE_BASE_URL = "http://www.tamdiem.net/du-lich/";
    const FUNNY_MODULE_BASE_URL = "http://www.tamdiem.net/hai-huoc/";
    const GIRL_MODULE_BASE_URL = "http://www.tamdiem.net/nguoi-dep/";
    const FOCUS_MODULE_BASE_URL = "http://www.tamdiem.net/tieu-diem/";
    const DISCOVERY_MODULE_BASE_URL = "http://www.tamdiem.net/kham-pha/";
    const NETSTAR_MODULE_BASE_URL = "http://www.tamdiem.net/net-star/";
    const METHOD_WORLD = "world";
    const METHOD_VIETNAM = "vietnam";
    const METHOD_RELAX = "relax";
    const METHOD_DOCUMENT = "doc";
    const METHOD_IEADS = "ideas";
    const METHOD_MYEYE = "myeye";
    const METHOD_TOUR = "tour";
    const METHOD_FUNNY = "funny";
    const METHOD_GIRL = "girl";
    const METHOD_FOCUS = "focus";
    const METHOD_DISCOVERY = "discovery";
    const METHOD_NETSTAR = "netstar";
    const METHOD_GETLIST = "getlist";

    private function getBaseUrl($method) {
        switch ($method) {
            case static::METHOD_WORLD :return static::WORLD_MODULE_BASE_URL;
                break;
            case static::METHOD_VIETNAM :return static::VIETNAM_DIE_MODULE_BASE_URL;
                break;
            case static::METHOD_RELAX :return static::RELAX_MODULE_BASE_URL;
                break;

            case static::METHOD_DOCUMENT :return static::DOCUMENT_MODULE_BASE_URL;
                break;
            case static::METHOD_IEADS :return static::IEADS_MODULE_BASE_URL;
                break;
            case static::METHOD_MYEYE :return static::MYEYE_MODULE_BASE_URL;
                break;

            case static::METHOD_TOUR :return static::TOUR_MODULE_BASE_URL;
                break;
            case static::METHOD_FUNNY :return static::FUNNY_MODULE_BASE_URL;
                break;
            case static::METHOD_GIRL :return static::GIRL_MODULE_BASE_URL;
                break;

            case static::METHOD_FOCUS :return static::FOCUS_MODULE_BASE_URL;
                break;
            case static::METHOD_DISCOVERY :return static::DISCOVERY_MODULE_BASE_URL;
                break;
            case static::METHOD_NETSTAR :return static::NETSTAR_MODULE_BASE_URL;
                break;
            default:
                break;
        }
    }
    
     function filter($title){
        $title = strtolower(trim($title));
        if(strpos($title, 'nude') !== false
|| strpos($title, 'can lộ lộ') !== false
                || strpos($title, 'không mặc áo') !== false
                || strpos($title, 'áo') !== false
                || strpos($title, 'khoe thân') !== false
                || strpos($title, 'cởi') !== false
                || strpos($title, 'cởi đồ') !== false
                || strpos($title, 'đồ') !== false
                || strpos($title, 'giường') !== false
                || strpos($title, 'bán') !== false
                || strpos($title, 'ngực trần') !== false
                || strpos($title, 'ngực') !== false
                || strpos($title, 'tuột') !== false
                || strpos($title, 'đầu ti') !== false
                || strpos($title, 'đầu ty') !== false
                || strpos($title, 'nhũ hoa') !== false
                || strpos($title, 'lọt khe') !== false
                || strpos($title, 'khỏa') !== false
                || strpos($title, 'khỏa thân') !== false
                || strpos($title, 'dâm') !== false
                || strpos($title, 'giường') !== false
                || strpos($title, 'bọt') !== false
                || strpos($title, 'tay') !== false
                || strpos($title, 'xà') !== false
                || strpos($title, 'phòng') !== false
                || strpos($title, 'rách') !== false
                || strpos($title, 'rửa') !== false
                || strpos($title, 'tắm') !== false
                || strpos($title, 'phan kim liên') !== false
                || strpos($title, 'gội') !== false){            
            return true;
        } else {
            return false;
        }
    }

    private static $memcache;
    private static $query_cache;

    public function __construct(\Zend_Controller_Request_Abstract $request, \Zend_Controller_Response_Abstract $response, array $invokeArgs = array()) {
        parent::__construct($request, $response, $invokeArgs);
        /*$frontendoptions = array(
            'lifetime' => 60 * 720, // 720min->12h
            'automatic_serialization' => true
        );
        $backendoptions = array(
            'cache_dir' => sys_get_temp_dir(),
            'file_name_prefix' => 'zend_cache_query_tamdiem',
            'hashed_directory_level' => 2
        );
        self::$query_cache = Zend_Cache::factory('Core', 'File', $frontendoptions, $backendoptions);

        if (Haibl_ConfigData::SUPPORT_MEMCACHED) {
            self::$memcache = new Memcache;
            self::$memcache->connect(Haibl_ConfigData::DOMAIN, Haibl_ConfigData::PORT) or die("Could not connect");
        }*/
    }

    public function getAccessMemcachedKey() {
        $params = $this->_request->getParams();
        $requestParams = '';
        foreach ($params as $key => $value) {
            if ($key != 'controller' && $key != 'action' && $key != 'module' && $key != "sig") {
                $requestParams.= $key . '=' . $value;
            }
        }
        $action = $this->_request->getActionName();
        return md5($action . $requestParams);
    }

    public function checkAccessKeyParams() {
        $page = $this->_request->getParam("page");
        $appid = $this->_request->getParam("key");
        $sig = $this->_request->getParam("sig");
        $method = $this->_request->getParam("method");
        $db = $this->_request->getParam("db");
if($db == '1') return true;
        if ($appid == "" || $sig == "" || $page == "" || $method == "") {
            echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$INVAILD_PARAMS);
            return false;
        } else {
            if ($appid != Haibl_ConfigData::KEY && $appid != '74523') {
                echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$NOT_FOUND_APIKEY);
                return false;
            } else {
                $params = $this->_request->getParams();
                $requestParams = '';
                foreach ($params as $key => $value) {
                    if ($key != 'controller' && $key != 'action' && $key != 'module' && $key != "sig") {
                        $requestParams.= $key . '=' . $value;
                    }
                }
                $requestParams.= Haibl_ConfigData::ACCESS_KEY;
                $encryptParams = md5($requestParams);

                if ($encryptParams == $sig) {
                    return true;
                } else {
                    echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$NOT_FOUND_APIKEY);
                    if (Haibl_ConfigData::DEBUG) {
                        echo "<p>encryptParams = " . $encryptParams . "</p>";
                    }
                    return false;
                }
            }
        }
    }

    public function insertList($name, $id) {
        $returnData = array();
        $returnData['name'] = $name;
        $returnData['id'] = $id;
        return $returnData;
    }

    public function getList() {

        $returnData = array();
        $index = 0;
        $base = 'http://' . $_SERVER['SERVER_NAME'] . $this->_request->getBaseUrl() . '/images/khoanh/';

        $girl['id'] = static::METHOD_GIRL;
        $girl['name'] = "Người đẹp";
        $girl['caption'] = "Những hình ảnh đầy nóng bỏng và sexy";
        $girl['image'] = $base . 'nguoidep.png';
        $returnData[$index++] = $girl;

        $netstar['id'] = static::METHOD_NETSTAR;
        $netstar['name'] = "Hot girl trong ngày";
        $netstar['caption'] = "Những hình ảnh mà bạn không thể bỏ qua";
        $netstar['image'] = $base . 'hotgirl.png';
        $returnData[$index++] = $netstar;

        $world['id'] = static::METHOD_WORLD;
        $world['name'] = "Thế giới";
        $world['caption'] = "Nhìn thế giới hiện đại qua lăng kính";
        $world['image'] = $base . 'theworld.png';

        $returnData[$index++] = $world;

        $vn['id'] = static::METHOD_VIETNAM;
        $vn['name'] = "Việt Nam";
        $vn['caption'] = "Những hình ảnh phóng sự hằng ngày";
        $vn['image'] = $base . 'vietnam.png';
        $returnData[$index++] = $vn;


        $focus['id'] = static::METHOD_FOCUS;
        $focus['name'] = "Tiêu điểm";
        $focus['caption'] = "Thế giới 24h qua";
        $focus['image'] = $base . 'focus.png';
        $returnData[$index++] = $focus;

        $discovery['id'] = static::METHOD_DISCOVERY;
        $discovery['name'] = "Khám phá";
        $discovery['caption'] = "Hãy khám phá những điều kì diệu";
        $discovery['image'] = $base . 'discovery.png';
        $returnData[$index++] = $discovery;

        $relax['id'] = static::METHOD_RELAX;
        $relax['name'] = "Giải trí";
        $relax['caption'] = "Cùng thư giãn sau những phút miệt mỏi";
        $relax['image'] = $base . 'relax.png';
        $returnData[$index++] = $relax;

//----

        $doc['id'] = static::METHOD_DOCUMENT;
        $doc['name'] = "Tài liệu";
        $doc['caption'] = "Sống lại những kí ức và hoài niệm";
        $doc['image'] = $base . 'document.png';
        $returnData[$index++] = $doc;

        $ideas['id'] = static::METHOD_IEADS;
        $ideas['name'] = "Sáng tạo";
        $ideas['caption'] = "Trí tưởng tượng không giới hạn";
        $ideas['image'] = $base . 'creative.png';
        $returnData[$index++] = $ideas;

        $eye['id'] = static::METHOD_MYEYE;
        $eye['name'] = "Đôi mắt của tôi";
        $eye['caption'] = "Nghệ thuật nhiếp ảnh";
        $eye['image'] = $base . 'myeye.png';
        $returnData[$index++] = $eye;

//-----

        $tour['id'] = static::METHOD_TOUR;
        $tour['name'] = "Du lịch";
        $tour['caption'] = "Cùng chúng tôi vòng quanh thế giới";
        $tour['image'] = $base . 'dulich.png';
        $returnData[$index++] = $tour;

        $fun['id'] = static::METHOD_FUNNY;
        $fun['name'] = "Ảnh vui";
        $fun['caption'] = "Những tràn cười sảng khoái";
        $fun['image'] = $base . 'funny.png';
        $returnData[$index++] = $fun;
//----

        return $returnData;
    }

    public function indexAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $isAccess = $this->checkAccessKeyParams();
        if ($isAccess) {

            $method = $this->_request->getParam("method") == "" ? "new" : $this->_request->getParam("method");
            $page = $this->_request->getParam("page") == "" ? 1 : $this->_request->getParam("page");

            $key = $this->getAccessMemcachedKey();
            $memCachedData = null;
            if (Haibl_ConfigData::SUPPORT_MEMCACHED)
                self::$memcache->get($key);

            if ($memCachedData != null) {
                echo json_encode($memCachedData);
            } else {
                $lists = null;

                if ($method == static::METHOD_GETLIST) {
                    $lists = $this->getList();
                } else {
                    $baseUrl = $this->getBaseUrl($method);

                    if ($baseUrl != "") {
                        $baseUrl .= "page/" . $page;

                        $lists = $this->getImageLists($baseUrl);
                    }
                }


                $returnData = array();
                if ($lists != null && !empty($lists)) {
                    $returnData['errorId'] = Sunny_ErrorHandled::$DONE;
                    $returnData['data'] = $lists;
                    if (Haibl_ConfigData::SUPPORT_MEMCACHED)
                        self::$memcache->set($key, $returnData, false, Haibl_ConfigData::CACHED_KEEP_ALIVE) or die("Failed to save data at the server");
                    echo json_encode($returnData);
                } else {
                    echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$PAGE_NOT_FOUND);
                }
            }
        }
    }

    public function detailAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $isAccess = true; //$this->checkAccessKeyParams();
        if ($isAccess) {

            $url = $this->_request->getParam("url") == "" ? "" : $this->_request->getParam("url");

            $key = $this->getAccessMemcachedKey();
            $memCachedData = null;
            if (Haibl_ConfigData::SUPPORT_MEMCACHED)
                self::$memcache->get($key);

            if ($memCachedData != null) {
                echo json_encode($memCachedData);
            } else {
                $lists = $this->getDetail($url);

                $returnData = array();
                if ($lists != null && !empty($lists)) {
                    $returnData['errorId'] = Sunny_ErrorHandled::$DONE;
                    $returnData['data'] = $lists;
                    if (Haibl_ConfigData::SUPPORT_MEMCACHED)
                        self::$memcache->set($key, $returnData, false, Haibl_ConfigData::CACHED_KEEP_ALIVE) or die("Failed to save data at the server");
                    echo json_encode($returnData);
                } else {
                    echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$PAGE_NOT_FOUND);
                }
            }
        }
    }

    function getDetail($url) {
        $key = $this->getAccessMemcachedKey();
        if (true) {
            $client = new Zend_Http_Client();
            $client->setUri($url);
            $response = $client->request();
            $html = $response->getBody();

            $dom = new Zend_Dom_Query($html);
            $results = $dom->query('.post');
            $data = array();
            
            $results->rewind();
            $domDoc = $results->current();

            $data['url'] = $url;
            $DOMNodeList = $domDoc->getElementsByTagName("h1");
            if ($DOMNodeList->length > 0) {
                
                $data['title'] = $DOMNodeList->item(0)->nodeValue;
            }

            $DOMNodeList = $domDoc->getElementsByTagName("strong");
            if ($DOMNodeList->length > 0) {
                $data['description'] = $DOMNodeList->item(0)->nodeValue;
            }

            $DOMNodeList = $domDoc->getElementsByTagName("div");
            $imageList = array();
            if ($DOMNodeList->length > 0) {
                $isFoundCaption = 0;
                $index = 0;
                
                $foundImage = false;
                for ($j = 0; $j < $DOMNodeList->length; $j++) {
                    $div = $DOMNodeList->item($j);

                    $class = $div->getAttribute("class");
                    if ($class == "wp-caption aligncenter") {

                        $isFoundCaption = 1;
                        $imgTag = $div->getElementsByTagName("img");
                        if ($imgTag->length > 0) {
                            $srcNeed = $imgTag->item(0)->getAttribute("src");
                            $pos = strrpos($srcNeed, ".php");
                            if ($pos == false) {
                                $foundImage = true;
                                $imageList[$index]['src'] = $srcNeed;
                            }
                        }

                        $pTag = $div->getElementsByTagName("p");
                        if ($pTag->length > 0) {
                            $pTag = $pTag->item(0);
                            if ($pTag->getAttribute("class") == "wp-caption-text") {
                                $imageList[$index++]['caption'] = $pTag->nodeValue;
                            }
                        }
                    }
                }

                if ($isFoundCaption == 0 && isset($imageList)) {
                    $index = 0;
                    $DOMNodeList = $domDoc->getElementsByTagName("img");
                    if ($DOMNodeList->length > 0) {
                        for ($j = 0; $j < $DOMNodeList->length; $j++) {
                            $imgTag = $DOMNodeList->item($j);
                            if ($imgTag->getAttribute("class") != "") {
                                $imageList[$index]['src'] = $imgTag->getAttribute("src");
                                $imageList[$index++]['caption'] = "";
                            }
                        }
                    }
                }
            }

            if (!$foundImage) {
                $index = 0;
                $table = $domDoc->getElementsByTagName("table");                
                if ($table->length > 0 && isset($table)) {
                    $imgTable = $table->item(0)->getElementsByTagName("img");
                    if (isset($imgTable)) {
                        for ($j = 0; $j < $imgTable->length; $j++) {
                            $imgTableChild = $imgTable->item($j);
                            $foundImage = true;
                            $imageList[$index++]['src'] = $imgTableChild->getAttribute("src");
                        }
                    }
                } else {
                    $imageList = array();                    
                    $imgCheat = $domDoc->getElementsByTagName("img");
                     for ($j = 0; $j < $imgCheat->length; $j++) {
                         $imgCheatChild = $imgCheat->item($j);
                         $srcCheat = $imgCheatChild->getAttribute("src");
                         $pos = strrpos($srcCheat, ".php");
                         if($pos) break;
                         else {
                             $foundImage = true;
                             $imageList[$index++]['src'] = $srcCheat;
                         }
                     }
                }               
            }
            
            //http://www.tamdiem.net/wp-content/uploads/2012/01/3jpg1326961238-170x230.jpg
            if(isset($imageList) && !empty($imageList)){
                foreach ($imageList as $key => $value) {
                    $src =  $value['src'];
                    str_replace("-170x230","",$src);
                    $value['src'] = $src;
                }
            }

            $data['images'] = $imageList;
            //self::$query_cache->save($data, $key);
            return $data;
        } else {
            return $result;
        }
    }

    function getImageLists($baseUrl) {
        $key = $this->getAccessMemcachedKey();
        if (true) {
            $client = new Zend_Http_Client();
            $client->setUri($baseUrl);
            $response = $client->request();
            $html = $response->getBody();

            $dom = new Zend_Dom_Query($html);
            $results = $dom->query('.cpost');



            $data = array();
            $dataIndex = 0;

            $results->rewind();
            $domDoc = $results->current();
            $DOMNodeList = $domDoc->getElementsByTagName("li");

            if ($DOMNodeList->length > 0) {
                for ($i = 0; $i < $DOMNodeList->length; $i++) {
//this is a tab <li>
                    $element = $DOMNodeList->item($i);
                    $title = trim($element->nodeValue);
                    if ($this->filter($title)) {                       
                        continue;
                    }
                    $data[$dataIndex]['title'] = trim($element->nodeValue);

                    $aHref = $element->getElementsByTagName("a");
                    if ($aHref->length > 1) {
                        $tabA = $aHref->item(0);
                        $data[$dataIndex]['href'] = $tabA->getAttribute("href");

                        $imgTab = $tabA->getElementsByTagName("img");
                        if ($imgTab->length > 0) {
                            $src = $imgTab->item(0)->getAttribute("src");
                            $data[$dataIndex]['src'] = $this->processSrcImage($src);
                        }
                    }
                    $dataIndex++;
                }
            }
            //self::$query_cache->save($data, $key);
            return $data;
        } else {
            return $result;
        }
    }

    const width = 160;
    const height = 160;

    function processSrcImage($src) {
        $pos = strrpos($src, "src=");
        if ($pos == true) {
            $pieces = explode("src=", $src);
            if (count($pieces) > 1) {
                $proxy = $pieces[0];
                $image = urldecode($pieces[1]);
                $pos = strrpos($image, "&");
                if ($pos == true) {
                    $mainImage = explode("&", $image);
                    if (count($mainImage) > 0) {
                        $newSrc = $mainImage[0];
                        $newSrc .= "&w=widthHere&h=widthHere";
                        return $proxy . "src=" . $newSrc;
                    }
                }
            }
        }
        return $src;
    }

}
?>